import hashlib
import hmac
import random

from django.db import models
from django.forms import ModelForm
from django.conf import settings

class HashlibProxy:
    def __init__(self, which):
        self.which = which
        self.digest_size = self.which().digest_size
    
    def new(self, *args, **kwargs):
        return self.which(*args, **kwargs)        

#Python 2.4 compatibility
md5 = hashlib.md5
try:
    getattr(md5, 'new')
except AttributeError:
    md5 = HashlibProxy(hashlib.md5)
    
class Paste(models.Model):
    
    hash = models.CharField(max_length=32, unique=True, primary_key=True, editable=False)
    edit_hash = models.CharField(max_length=32, unique=True, editable=False)
    timestamp = models.DateTimeField(auto_now=True, editable=False)

    title = models.CharField(max_length=512, blank=True)
    data = models.TextField()
    private = models.BooleanField()

    def __unicode__(self):
        return u"%s" % (self.title)

    def save(self, *args, **kwargs):              
        if len(self.hash) == 0:
            self.hash = hmac.new(settings.SECRET_KEY, str(random.random()) + settings.SALT_KEY, md5).hexdigest()
            self.edit_hash = hmac.new(settings.SECRET_KEY, str(random.random()) + settings.SALT_KEY, md5).hexdigest()
            
        super(Paste, self).save(*args, **kwargs)

class PasteForm(ModelForm):
    class Meta:
        model = Paste
